import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { middleWareAll } from './middleware/appLimit';
import * as session from 'express-session';
import * as cors from 'cors'
import { join } from 'path'
import { FormatRes } from './common/response';
import { HttpFilter } from './common/filter';
import { WINSTON_LOGGER_TOKEN } from './log/logger.module';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    // logger: ['log', 'warn', 'error', 'debug']
    bufferLogs: true
  });
  
  app.useLogger(app.get(WINSTON_LOGGER_TOKEN)); // 日志模块

  app.use(middleWareAll);
  app.useGlobalInterceptors(new FormatRes()); // 响应拦截,统一处理响应的参数
  app.useGlobalFilters(new HttpFilter()); // 异常拦截，捕获作为HttpException类实例的异常
  // 中间件 cors 允许跨域
  app.use(cors({
    origin: '*',
    methods: "GET,POST,PUT,HEAD,PATCH,DELETE"
  })); 
  app.useStaticAssets('public', { prefix: '/static'}); // 本地起一个前端服务 http://localhost:8080/static/index.html
  app.useStaticAssets(join(__dirname, 'images'),{
    prefix:"/images"
  })
  app.use(session({ 
    secret: "test-session", 
    name: "test-session", 
    rolling: true, 
    resave: false,
    cookie: { maxAge: null } 
  }));

  // 生成 api 文档
  const options = new DocumentBuilder().setTitle('nest接口文档').setDescription('接口文档汇总').setVersion('1.0.0').build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/nest-apis', app, document);

  // 获取参数
  const configService = app.get(ConfigService);
  const port = configService.get('port')

  await app.listen(port);
}

bootstrap();
